package com.yks.hbo.amazon.util;

import com.alibaba.fastjson.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.yks.hbo.amazon.dto.PlsAmazonAdAccTokenDTO;
import com.yks.hbo.amazon.vo.TokenResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
* @Description: AmazonAdvertisingApiUtil
* @Author: gaoliangyou
* @Date: 2020/12/8 11:25
*/
public class AmazonAdvertisingApiUtil {
    private static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
    public static final Logger LOGGER = LoggerFactory.getLogger(AmazonAdvertisingApiUtil.class);

    public static TokenResponse getAccessToken(String code, String redirectUri, String url) throws Exception {
        LOGGER.info("开始获取token，，，");
        if(StringUtils.isEmpty(code)) {
            return null;
        }
        StringBuffer buffer = new StringBuffer();
        buffer.append("grant_type=")
                .append("authorization_code")
                .append("&")
                .append("code=")
                .append(code)
                .append("&")
                .append("redirect_uri=")
                .append(redirectUri)
                .append("&")
                .append("client_id=")
                .append(AmazonAdvertisingApiConstant.App.CLIENT_ID)
                .append("&")
                .append("client_secret=")
                .append(AmazonAdvertisingApiConstant.App.CLIENT_SECRET);

        HttpResponse<String> response = Unirest.post(url)
                .header("Content-Type", "Content-Type:application/x-www-form-urlencoded")
                .body(buffer.toString())
                .asString();
        JSONObject jsonObject = JSONObject.parseObject(response.getBody());
        String accessToken = jsonObject.getString("access_token");
        String refreshToken = jsonObject.getString("refresh_token");
        String tokenType = jsonObject.getString("token_type");
        Integer expiresIn = jsonObject.getInteger("expires_in");
        LOGGER.info("AmazonAdvertisingApiUtil > getAccessToken Amazon 广告请求授权和刷新令牌回调成功 accessToken:{}, refreshToken:{}, tokenType:{}, expiresIn:{}, ", accessToken, refreshToken, tokenType, expiresIn);
        return null;
    }

    public static String getAmazonAdToken(String code, String redirectUri, String url) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("code", code);
        paramMap.put("redirect_uri", redirectUri);
        paramMap.put("client_id", AmazonAdvertisingApiConstant.App.CLIENT_ID);
        paramMap.put("client_secret", AmazonAdvertisingApiConstant.App.CLIENT_SECRET);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", CONTENT_TYPE);
        LOGGER.info("url:{}",url);
        LOGGER.info("paramMap:{}",JSONObject.toJSONString(paramMap));
        LOGGER.info("headerMap:{}",JSONObject.toJSONString(headerMap));
        String result = HttpUtility.postFormWithRetry(url, paramMap, headerMap, 1);
        if (StringUtils.isEmpty(result)) {
            LOGGER.error("AmazonAdvertisingApiUtil > getAmazonAdToken fail");
        }
        return result;
    }




    /**
     * 刷新token
     * @return
     */
    public static String refreshToken(String url, String refreshToken) throws Exception {
        Map<String, String> header = new HashMap<>(2);
        header.put("Content-Type", "application/x-www-form-urlencoded");
        Map<String, String> param = new HashMap<>(8);
        param.put("grant_type", "refresh_token");
        param.put("client_id", AmazonAdvertisingApiConstant.App.CLIENT_ID);
        param.put("client_secret", AmazonAdvertisingApiConstant.App.CLIENT_SECRET);
        param.put("refresh_token", refreshToken);
        String result = HttpClientUtil.doPost(url, param, header);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("access_token");
    }

    /**
     * 获取默认头信息
     * @return Map<String, String>
     * @author: songxulin
     * @date :  2020-10-01 17:21
     */
    public static Map<String, String> getDefeatHeader(String token) {
        Map<String, String> header = new HashMap<>(4);
        header.put("Authorization", "Bearer " + token);
        header.put("Amazon-Advertising-API-ClientId", AmazonAdvertisingApiConstant.App.CLIENT_ID);
        return header;
    }

    public static Map<String, String> getHeader(PlsAmazonAdAccTokenDTO accTokenDTO) {
        Map<String, String> header = new HashMap<>(4);
        header.put("Authorization", "Bearer " + accTokenDTO.getAccessToken());
        header.put("Amazon-Advertising-API-ClientId", AmazonAdvertisingApiConstant.App.CLIENT_ID);
        header.put("Amazon-Advertising-API-Scope", accTokenDTO.getProfileId().toString());
        return header;
    }

    public static String getUrlPathPrefix(String region) {
        String urlPathPrefix = null;
        switch (region){
            case "NA":
                urlPathPrefix = AmazonAdvertisingApiConstant.NaUrlPathPrefix.NA_AD_API_URL;
                break;
            case "EU":
                urlPathPrefix = AmazonAdvertisingApiConstant.EuUrlPathPrefix.EU_AD_API_URL;
                break;
            case "FE":
                urlPathPrefix = AmazonAdvertisingApiConstant.FeUrlPathPrefix.FE_AD_API_URL;
                break;
        }
        return urlPathPrefix;
    }

}
